<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org" lang="zh-CN">
<head>
    <meta charset="utf-8">
    <title>Layui 集成 FullCalendar 示例</title>

    <link rel="stylesheet" th:href="@{/pear/component/layui/css/layui.css}"/>
    <link rel="stylesheet" th:href="@{/pear/component/fullcalendar/css/fullcalendar.min.css}"/>
    <style>
        /* 固定表单在顶部 */
        .fixed-form {
            position: fixed;
            top: 0;
            width: 100%;
            background: #fff;
            z-index: 1000;
            padding: 10px;
            box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
            display: flex;
            justify-content: center;
            align-items: center;
        }

        /* 为日历添加一些顶部间距，避免被固定表单遮挡 */
        #calendar {
            margin-top: 80px; /* 根据固定表单的高度调整 */
        }

        /* 图片预览容器样式 */
        #imagePreview {
            position: fixed;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            width: 80%; /* 调整宽度 */
            max-width: 600px; /* 最大宽度 */
            height: auto;
            background: rgba(0, 0, 0, 0.7);
            display: none;
            justify-content: center;
            align-items: center;
            z-index: 1001;
            padding: 20px;
            border-radius: 10px;
            box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
        }

        #imagePreview img {
            max-width: 100%;
            max-height: 80%;
            border-radius: 5px;
        }

        /* 关闭按钮样式 */
        #closePreview {
            position: absolute;
            top: 10px;
            right: 10px;
            color: white;
            font-size: 24px;
            cursor: pointer;
            background: red; /* 添加背景颜色 */
            padding: 5px;
            border-radius: 50%; /* 圆形背景 */
            width: 30px;
            height: 30px;
            line-height: 24px;
            text-align: center;
        }
    </style>
</head>

<body>
<!-- 固定在顶部的表单 -->
<div class="fixed-form">
    <button id="jumpButton" class="layui-btn layui-btn-sm" style="margin-right: 10px;margin-bottom: 15px">预约时间
    </button>
    <div class="layui-form-item">
        <label class="layui-form-label">会议室：</label>
        <div class="layui-input-block">
            <select name="location" id="meeting" lay-filter="meeting" class="layui-select">
                <!-- 动态加载会议室选项 -->
            </select>
        </div>
    </div>
    <div class="layui-form-item">
        <a href="javascript:void(0)" id="roomImageLink"
           style="text-decoration:underline;margin-left: 50px;">查看图片</a>
    </div>

    <!-- 图片预览容器 -->
    <div id="imagePreview">
        <img id="previewImg" src="" alt="会议室图片">
        <span id="closePreview">&times;</span>
    </div>
</div>

<div id="calendar"></div>

<script th:src="@{/pear/component/jquery/jquery.min.js}"></script>
<script th:src="@{/pear/component/layui/layui.js}"></script>
<script th:src="@{/pear/component/fullcalendar/js/moment.min.js}"></script>
<script th:src="@{/pear/component/fullcalendar/js/index.global.min.js}"></script>
<script th:inline="javascript">

    layui.use(['layer', 'form'], function () {
        let baseURL = /*[[@{/}]]*/ '';
        var layer = layui.layer;
        var form = layui.form;
        // 定义一个全局数组，存放会议室预约的值
        let reservationEvents = [];

        // 从后端获取会议室预约数据
        function loadReservationEvents(roomId) {
            return new Promise((resolve, reject) => {
                $.ajax({
                    url: baseURL + 'meeting/reservation/reservationListByUserIdAndRoomId?roomId=' + roomId,
                    dataType: 'json',
                    type: 'get',
                    success: function (result) {
                        console.log(result.data)
                        if (result.code === 1000) {
                            reservationEvents = result.data.map(reservation => ({
                                title: reservation.purpose,
                                start: reservation.reservationData + 'T' + reservation.startTime,
                                end: reservation.reservationData + 'T' + reservation.endTime,
                                extendedProps: { // 自定义属性
                                    username: reservation.username, // 预约人用户名
                                    phone: reservation.phone, // 预约人电话
                                    timeRange: reservation.startTime + '-' + reservation.endTime // 时间范围（开始时间 - 结束时间）
                                }
                            }));
                            resolve();
                        } else {
                            layer.msg(result.msg, {icon: 2});
                            reject();
                        }
                    },
                    error: function () {
                        layer.msg('加载失败', {icon: 2});
                        reject();
                    }
                });
            });
        }

        $.ajax({
            url: baseURL + 'department/session/getDepartmentId', // 后端接口地址
            type: 'get',
            contentType: 'application/json',
            success: function (response) {
                window.departmentId = response.data
                // 加载会议室列表的函数
                $.ajax({
                    url: baseURL + 'meeting/reservation/getMeetByDepartment?departmentId=' + response.data, // 后端接口地址
                    type: 'GET',
                    dataType: 'json',
                    success: function (data) {
                        var select = $('#meeting');
                        let room = data.data;

                        // 清空下拉框并添加选项
                        select.empty();
                        $.each(room, function (index, rooms) {
                            select.append(
                                '<option value="' + rooms.roomId + '">' +
                                rooms.roomName +
                                ' (设备: ' + (rooms.equipmentNameList.length > 0 ? rooms.equipmentNameList.join(', ') : '无') +
                                ', 容量: ' + rooms.capacity +
                                ', 联系人: ' + rooms.contactName +
                                ', 电话: ' + rooms.contactPhone + ')' +
                                '</option>'
                            );
                        });

                        // 初始化表单渲染
                        form.render('select');

                        // 设置默认选中第一个选项，并触发 change 事件
                        if (room.length > 0) {
                            select.val(room[0].roomId).change();
                            if (room[0].image) {
                                $('#roomImageLink').off('click').on('click', function () {
                                    $('#previewImg').attr('src', baseURL + room[0].image);
                                    $('#imagePreview').show();
                                });
                            }
                        }
                    },
                });

            },
        });
        let closeTime;
        // 监听会议室下拉框的变化
        $('#meeting').on('change', function () {
            let selectedRoomId = $(this).val();
            $.ajax({
                url: baseURL + 'meeting/meetRoom/getMeetingRoomById?roomId=' + selectedRoomId,
                type: 'get',
                success: function (result) {
                    if (result.data.closeTime != null) {
                        closeTime = result.data.closeTime
                    }
                    // 关闭之前的图片预览
                    $('#imagePreview').hide();
                    let res = result.data;
                    if (res.image) {
                        // 绑定新的点击事件
                        $('#roomImageLink').off('click').on('click', function () {
                            $('#previewImg').attr('src', baseURL + res.image);
                            $('#imagePreview').show();
                        });
                    } else {
                        $('#roomImageLink').off('click').on('click', function () {
                            layer.msg('该会议室无图片');
                        });
                    }
                }
            });
            loadReservationEvents(selectedRoomId).then(() => {
                renderCalendar();
            })
        });

        // 渲染日历
        function renderCalendar() {
            var calendarEl = document.getElementById('calendar');
            var calendar = new FullCalendar.Calendar(calendarEl, {
                headerToolbar: {
                    left: 'prev,next today',
                    center: 'title',
                    right: 'dayGridMonth,timeGridWeek,timeGridDay'
                },
                initialDate: new Date(),
                editable: true,
                events: reservationEvents,
                eventClick: function (info) {
                    let title = info.event.title; // 会议主题
                    let username = info.event.extendedProps.username; // 预约人用户名
                    let phone = info.event.extendedProps.phone; // 预约人电话
                    let timeRange = info.event.extendedProps.timeRange; // 时间范围（开始时间 - 结束时间）

                    // 构造显示的文本
                    let alertText = `会议主题: ${title}<br>` +
                        `预约人: ${username}<br>` +
                        `时间范围: ${timeRange}<br>` +
                        `电话: ${phone}`;

                    // 使用 layer 弹窗显示详细信息
                    layer.alert(alertText);
                },
                dateClick: function (info) {
                    let date = new Date(info.dateStr);
                    let currentDate = new Date();
                    date.setHours(0, 0, 0, 0);
                    currentDate.setHours(0, 0, 0, 0);
                    if (currentDate > date) {
                        layer.msg('请选择有效时间', {icon: 2});
                        return;
                    }
                    if (closeTime != null && closeTime !== undefined) {
                        let clickDate = date.toLocaleString('zh-Hans-CN', {
                            year: 'numeric',
                            month: '2-digit',
                            day: '2-digit',
                            hour: '2-digit',
                            minute: '2-digit',
                            second: '2-digit',
                            hour12: false
                        })
                            .replace(/\//g, '-')
                            .replace(/ /g, 'T');
                        const start = new Date(closeTime.split(' - ')[0].replace(' ', 'T'));
                        const end = new Date(closeTime.split(' - ')[1].replace(' ', 'T'));
                        const click = new Date(clickDate);   // clickDate 可以是 Date 或 ISO 字符串

                        if (click >= start && click <= end) {
                            layer.msg('会议室在' + closeTime + '关闭，请选择有效时间', {icon: 2});
                            return;
                        }
                    }
                    window.formatedDate = moment(date).format('YYYY-MM-DD');
                    layer.open({
                        type: 2,
                        title: '会议室预约',
                        shade: 0.1,
                        shadeClose: true,
                        area: ['100%', '100%'],
                        content: '../reservation/index',
                        success: function (layero, index) {
                            var closeBtn = layero.find('.layui-layer-close');
                            closeBtn.on('click', function () {
                                $.ajax({
                                    url: baseURL + 'meeting/reservation/clear',
                                    dataType: 'json',
                                    contentType: 'application/json',
                                    type: 'post',
                                    async: true,
                                    success: function (result) {
                                        if (result.code === 1000) {
                                            console.log('预约集合已清空');
                                        } else {
                                            console.log(result.msg);
                                        }
                                    }
                                });
                                layer.close(index);
                            });
                        }
                    });
                }
            });
            calendar.render();
        }

        // 关闭图片预览
        $('#closePreview').on('click', function () {
            $('#imagePreview').hide();
        });
        // 绑定跳转按钮的点击事件
        document.getElementById('jumpButton').onclick = function () {
            location.href = baseURL + 'page/meeting/week';
        };
    });
</script>
</body>
</html>